package so.sao.code.service.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import so.sao.code.service.domain.entity.QrcodeDomain;
import so.sao.code.service.infrastructure.model.vo.QrcodeDomainVO;
import so.sao.code.service.repository.QrcodeDomainDao;
import so.sao.code.service.service.QrcodeDomainService;
import so.sao.top.core.model.enums.CommonStatus;

@Service
public class QrcodeDomainServiceImpl implements QrcodeDomainService {

	@Autowired
	private QrcodeDomainDao qrcodeDomainDao;

	@Value("${sao.code.key.default-domain}")
	private String defaultDomain;

	@Override
	public List<QrcodeDomainVO> findQrcodeDomains() {
		QrcodeDomainVO def = new QrcodeDomainVO();
		def.setDomainUrl(defaultDomain);
		def.setDef(true);
		List<QrcodeDomain> qrcodeDomains = qrcodeDomainDao.findAllByStatus(CommonStatus.EFFECTIVE.getValue());
		List<QrcodeDomainVO> result = qrcodeDomains.stream().map(item -> {
			QrcodeDomainVO qrcodeDomainVO = new QrcodeDomainVO();
			BeanUtils.copyProperties(item, qrcodeDomainVO);
			return qrcodeDomainVO;
		}).collect(Collectors.toList());
		result.add(def);
		return result.stream().sorted(Comparator.comparing(item -> !item.isDef())).collect(Collectors.toList());
	}

	@Override
	public QrcodeDomain save(QrcodeDomain qrcodeDomain) {
		return qrcodeDomainDao.save(qrcodeDomain);
	}

}
